import cv2
import subprocess

# FFmpeg 推流命令
# 替换 <server-ip> 和 <stream-key> 为你的 RTMP 服务器地址和流密钥
ffmpeg_command = [
    'ffmpeg',
    '-y',
    '-f', 'rawvideo',
    '-vcodec', 'rawvideo',
    '-pix_fmt', 'bgr24',
    '-s', '640x480',  # 尺寸
    '-r', '100',  # 帧率
    '-i', '-',  # 标准输入
    '-c:v', 'libx264',
    '-preset', 'veryfast',
    '-tune', 'zerolatency',
    '-f', 'flv',
    # '-pix_fmt', 'yuv420p',
    'rtmp://124.221.6.242:1935/live/rtmp'
    # 'rtmp://192.168.31.229:1935/live/rtmp'
    # 'rtmp://127.0.0.1:1935/live/rtmp'
]

# 打开摄像头
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

# 启动 FFmpeg 子进程
process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    # print('work')
    # 将帧写入 FFmpeg 的 stdin
    process.stdin.write(frame.tobytes())

# 释放摄像头和关闭子进程
cap.release()
process.stdin.close()
process.wait()
